import React, { useRef, useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getImgItem } from "@/store/modules/images";
const ChentsMob = () => {
  const scrollRef = useRef(null);
  const dispatch = useDispatch();
  const item = useSelector((state) => state.images.item);
  useEffect(() => {
    dispatch(getImgItem());
  }, [dispatch]);
  const [showLeftArrow, setShowLeftArrow] = useState(false);
  const [showRightArrow, setShowRightArrow] = useState(false);

  // 保存上次滚动位置，防止重复更新
  const lastScrollLeft = useRef(0);
  const lastShowLeft = useRef(false);
  const lastShowRight = useRef(false);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;

    let rafId = null;

    const checkArrows = () => {
      const { scrollLeft, scrollWidth, clientWidth } = el;

      const canScrollLeft = scrollLeft > 5;
      const canScrollRight = scrollLeft + clientWidth < scrollWidth - 5;

      // 只在状态变化时更新，避免无限触发
      if (canScrollLeft !== lastShowLeft.current) {
        setShowLeftArrow(canScrollLeft);
        lastShowLeft.current = canScrollLeft;
      }
      if (canScrollRight !== lastShowRight.current) {
        setShowRightArrow(canScrollRight);
        lastShowRight.current = canScrollRight;
      }
    };

    // 初次调用
    checkArrows();

    const onScroll = () => {
      if (rafId) cancelAnimationFrame(rafId);
      rafId = requestAnimationFrame(() => {
        checkArrows();
      });
    };

    el.addEventListener("scroll", onScroll);
    return () => {
      el.removeEventListener("scroll", onScroll);
      if (rafId) cancelAnimationFrame(rafId);
    };
  }, []);

  const scrollLeft = () => {
    scrollRef.current.scrollBy({ left: -132, behavior: "smooth" });
  };

  const scrollRight = () => {
    scrollRef.current.scrollBy({ left: 132, behavior: "smooth" });
  };

  return (
    <div
      className="chents-mob"
      style={{
        position: "relative",
        height: "170px",
        width: "100%",
        padding: "10px 0 20px",
      }}
    >
      <div
        className="scroll-wrapper"
        ref={scrollRef}
        style={{
          display: "flex",
          overflowX: "auto",
          scrollSnapType: "x mandatory",
          scrollbarWidth: "none",
        }}
      >
        {showLeftArrow && (
          <button
            className="arrow-btn left"
            onClick={scrollLeft}
            style={{
              position: "absolute",
              left: 5,
              top: "50%",
              transform: "translateY(-50%)",
              background: "rgba(220, 219, 219, 0.4)",
              border: "none",
              borderRadius: "50%",
              cursor: "pointer",
              height: "34px",
              width: "34px",
              fontSize: 18,
              zIndex: 10,
              color: "#000",
            }}
          >
            &#10094;
          </button>
        )}
        {item.map((items, index) => (
          <div
            key={index}
            style={{
              height: 125,
              width: 120,
              flexShrink: 0,
              scrollSnapAlign: "start",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              userSelect: "none",
              flexDirection: "column",
              cursor: "pointer",
            }}
          >
            <img src={items.image} style={{ height: 80, width: 80 }} />
            <div style={{ marginTop: 6 }}>
              <a
                style={{
                  textDecoration: "none",
                  color: "#000",
                  cursor: "pointer",
                  fontSize: 14,
                }}
                href="#"
                onMouseEnter={(e) =>
                  (e.target.style.textDecoration = "underline")
                }
                onMouseLeave={(e) => (e.target.style.textDecoration = "none")}
              >
                {items.title}
              </a>
            </div>
          </div>
        ))}
        {showRightArrow && (
          <button
            className="arrow-btn right"
            onClick={scrollRight}
            style={{
              position: "absolute",
              right: 5,
              top: "50%",
              transform: "translateY(-50%)",
              background: "rgba(220,219,219,0.4)",
              border: "none",
              borderRadius: "50%",
              cursor: "pointer",
              height: "34px",
              width: "34px",
              fontSize: 18,
              zIndex: 10,
              color: "#000",
            }}
          >
            &#10095;
          </button>
        )}
      </div>
    </div>
  );
};

export default ChentsMob;
